import '../models/note.dart';
import '../services/database_service.dart';

class NoteRepository {
  final DatabaseService _dbService = DatabaseService();
  static const String _tableName = DatabaseService.notesTable;

  /// 添加笔记
  Future<int> addNote(Note note) async {
    final data = note.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有笔记
  Future<List<Note>> getAllNotes() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => Note.fromMap(data)).toList();
  }

  /// 根据ID获取笔记
  Future<Note?> getNoteById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? Note.fromMap(result) : null;
  }

  /// 根据分类获取笔记
  Future<List<Note>> getNotesByCategory(String category) async {
    final results = await _dbService.getByField(_tableName, 'category', category);
    return results.map((data) => Note.fromMap(data)).toList();
  }

  /// 搜索笔记
  Future<List<Note>> searchNotes(String keyword) async {
    final allNotes = await getAllNotes();
    return allNotes.where((note) => 
      note.title.toLowerCase().contains(keyword.toLowerCase()) ||
      note.content.toLowerCase().contains(keyword.toLowerCase())
    ).toList();
  }

  /// 根据标签搜索笔记
  Future<List<Note>> getNotesByTag(String tag) async {
    final allNotes = await getAllNotes();
    return allNotes.where((note) => 
      note.tags.toLowerCase().contains(tag.toLowerCase())
    ).toList();
  }

  /// 获取最近创建的笔记
  Future<List<Note>> getRecentNotes(int count) async {
    final allNotes = await getAllNotes();
    allNotes.sort((a, b) => b.created_at.compareTo(a.created_at));
    return allNotes.take(count).toList();
  }

  /// 获取最近更新的笔记
  Future<List<Note>> getRecentlyUpdatedNotes(int count) async {
    final allNotes = await getAllNotes();
    allNotes.sort((a, b) => b.updated_at.compareTo(a.updated_at));
    return allNotes.take(count).toList();
  }

  /// 更新笔记
  Future<void> updateNote(Note note) async {
    final updatedNote = note.copyWith(
      updated_at: DateTime.now().millisecondsSinceEpoch,
    );
    await _dbService.update(_tableName, updatedNote.toMap());
  }

  /// 删除笔记
  Future<void> deleteNote(int id) async {
    await _dbService.delete(_tableName, id);
  }
  
  /// 删除所有笔记
  Future<bool> deleteAllNotes() async {
    try {
      await _dbService.clearTable(_tableName);
      return true;
    } catch (e) {
      print('删除所有笔记失败: $e');
      return false;
    }
  }

  /// 批量添加笔记
  Future<List<int>> addNotes(List<Note> notes) async {
    final List<int> ids = [];
    for (final note in notes) {
      final id = await addNote(note);
      ids.add(id);
    }
    return ids;
  }

  /// 获取笔记总数
  Future<int> getNoteCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取分类列表
  Future<List<String>> getCategories() async {
    final allNotes = await getAllNotes();
    final categories = allNotes
        .map((note) => note.category)
        .where((category) => category.isNotEmpty)
        .toSet()
        .toList();
    categories.sort();
    return categories;
  }

  /// 获取所有标签
  Future<List<String>> getAllTags() async {
    final allNotes = await getAllNotes();
    final allTags = <String>{};
    
    for (final note in allNotes) {
      if (note.tags.isNotEmpty) {
        final tags = note.tags.split(',').map((tag) => tag.trim());
        allTags.addAll(tags);
      }
    }
    
    final tagList = allTags.toList();
    tagList.sort();
    return tagList;
  }

  /// 获取分类统计
  Future<Map<String, int>> getCategoryStats() async {
    final allNotes = await getAllNotes();
    final stats = <String, int>{};
    
    for (final note in allNotes) {
      if (note.category.isNotEmpty) {
        stats[note.category] = (stats[note.category] ?? 0) + 1;
      }
    }
    
    return stats;
  }

  /// 获取按日期分组的笔记
  Future<Map<String, List<Note>>> getNotesByDate() async {
    final allNotes = await getAllNotes();
    final groupedNotes = <String, List<Note>>{};
    
    for (final note in allNotes) {
      final date = DateTime.fromMillisecondsSinceEpoch(note.created_at);
      final dateKey = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      
      if (!groupedNotes.containsKey(dateKey)) {
        groupedNotes[dateKey] = [];
      }
      groupedNotes[dateKey]!.add(note);
    }
    
    return groupedNotes;
  }

  /// 清空所有笔记
  Future<void> clearAllNotes() async {
    await _dbService.clearTable(_tableName);
  }

  /// 导出笔记为文本
  Future<String> exportNotesToText() async {
    final allNotes = await getAllNotes();
    final buffer = StringBuffer();
    
    for (final note in allNotes) {
      buffer.writeln('标题: ${note.title}');
      buffer.writeln('分类: ${note.category}');
      buffer.writeln('标签: ${note.tags}');
      buffer.writeln('创建时间: ${DateTime.fromMillisecondsSinceEpoch(note.created_at)}');
      buffer.writeln('内容:');
      buffer.writeln(note.content);
      buffer.writeln('${'=' * 50}');
      buffer.writeln();
    }
    
    return buffer.toString();
  }
}